<?php
class DownloadRenderer extends Renderer
{
	/**
	 * @var DownloadRenderer
	 */
	private static $instance;
	
	/**
	 * 
	 * @var bool
	 */
	private $debugging = false;
	
	protected function __construct()
	{
		parent::__construct();
		array_shift($this->arguments);
	}
	
	/**
	 * @return DownloadRenderer
	 */
	public function getInstance()
	{
		if(!self::$instance)
		{
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	public function run()
	{
		$supportedTypes = array('pdf', 'docx'); // later docx en xlsx toevoegen?
		if(in_array($this->arguments[0], $supportedTypes))
		{
			switch($this->arguments[1])
			{
				case 'agenda':
					$this->runSchedule();
					break;
			}
		}
		$this->redirect();
	}
	
	protected function runSchedule()
	{
		switch($this->arguments[2])
		{
			case 'locatie':
				$this->runLocationSchedule($this->arguments[3], $this->arguments[4]);
				break;
			case 'team':
				$this->runTeamSchedule($this->arguments[3], $this->arguments[4]);
				break;
		}
		return;
	}
	
	protected function runLocationSchedule($nefubId, $date)
	{
		if(is_numeric($nefubId) && $date)
		{
			if($oLocation = Location::getByNefubId($nefubId))
			{
				$formattedDate = strftime("%A %e %B %Y", strtotime($date));
				$filename ='agenda '.$date.' '. $oLocation->name;
				
				$oSeason = Season::getInstance();
				$aGames = Game::getAll(array('date' => $date, 'location_nefub_id' => $oLocation->nefub_id), 'time` ASC, `field', 'asc');
				$title = 'Programma '.$formattedDate;
				$includeField = false;
				$footer = $title .' in '.$oLocation->name .', '.$oLocation->city.'. Gedownload van http://'.$_SERVER['HTTP_HOST'].'/locatie/'.$nefubId;
				$this->renderGames($filename, $title, $aGames, $footer);
			}
		}
		$this->redirect();
	}
	protected function runTeamSchedule($nefubId, $date)
	{
		if(is_numeric($nefubId) && $date)
		{
			if($oTeam = Team::getByNefubId($nefubId))
			{				
				$formattedDate = strftime("%A %e %B %Y", strtotime($date));
				
				$filename ='agenda '.$date.' '. $oTeam->name;
				$oSeason = Season::getInstance();

				$query = "SELECT Game.nefub_id FROM Game WHERE Game.date = '".$date."' 
							AND
								(	Game.team1_nefub_id = '".$oTeam->nefub_id."' OR
									Game.team2_nefub_id = '".$oTeam->nefub_id."' OR
									Game.ref_team_nefub_id = '".$oTeam->nefub_id."')
							ORDER BY Game.time, Game.field;
						";
				$rows = Database::select_rows_by_query($query);
				
				$aGames = array();				
				foreach($rows as $row)
				{
					$aGames[] = Game::getByNefubId($row['nefub_id']);
				}
				
				$title = 'Programma '.$formattedDate .' voor '.$oTeam->name .' ('.$oTeam->getCompetition()->name.')';
				
				$footer = $title .'. Gedownload van http://'.$_SERVER['HTTP_HOST'].'/team/'.$nefubId;
				$this->renderGames($filename, $title, $aGames, $footer, false);
			}
		}
		$this->redirect();
	}
	
	protected function renderGames($filename, $title, $aGames, $footer, $includeFieldPages = true)
	{
		if(count($aGames) && $aGames[0]->getLocation())
		{
			$location = utf8_decode($aGames[0]->getLocation()->name) .', '.utf8_decode($aGames[0]->getLocation()->city);
		}
		else
		{
			$location = 'Onbekend';
		}
		
		// PDF
		if($this->arguments[0] == 'pdf')
		{
	
			$pdf = new SchedulePDF();
			$pdf->SetTitle($title);
			$pdf->AddPageWithTitleAndLocation($title, $location);
			$pdf->SetFooterText($footer);
			
			
			$fieldsGames = $pdf->renderGamesPage($aGames, $includeFieldPages);
			foreach($fieldsGames as $field => $aFieldGames)
			{
				$pdf->AddPageWithTitleAndLocation($title, $location);
				$pdf->addFieldTitle($field);
				$pdf->renderGamesPage($aFieldGames, false);		
			}
			
			if(!$this->debugging)
			{
				error_reporting(0);
				header('Content-type: application/pdf');
				$filename .= '.pdf';
				$filename = str_replace('.pdf.pdf', '.pdf', $filename);
				header('Content-Disposition: attachment; filename="'.$filename.'"');
			}		
			$pdf->Output();
		}
		elseif($this->arguments[0] == 'docx')
		{
			$docx = new ScheduleDocx();
			//$docx->SetTitle($title);
			$docx->AddPageWithTitleAndLocation($title, $location);
			$docx->SetFooterText($footer);
			
			
			$fieldsGames = $docx->renderGamesPage($aGames, $includeFieldPages);
			foreach($fieldsGames as $field => $aFieldGames)
			{
				$docx->AddPageWithTitleAndLocation($title, $location);
				$docx->addFieldTitle($field);
				$docx->renderGamesPage($aFieldGames, false);		
			}
			
			
			if(!$this->debugging)
			{
				error_reporting(0);				
				header('Content-type: application/vnd.ms-word');
				$filename .= '.docx';
				$filename = str_replace('.docx.docx', '.docx', $filename);
				header('Content-Disposition: attachment; filename="'.$filename.'"');
			}	
			$docx->output();
		}
		
		exit;
	}
	
	
	
}